#include "cn8023a.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/gpio.h"

static const char *TAG = "CN8023A";
static SemaphoreHandle_t relay_mutex = NULL;

int cn8023a_init(void)
{
    relay_mutex = xSemaphoreCreateMutex();
    if (relay_mutex == NULL)
    {
        ESP_LOGE(TAG, "Mutex creation failed");
        return -1;
    }

    // GPIO配置
    gpio_config_t io_conf = {
        .pin_bit_mask = (1ULL << CONFIG_RELAY_INA_GPIO) | (1ULL << CONFIG_RELAY_INB_GPIO),
        .mode = GPIO_MODE_OUTPUT,
        .pull_up_en = GPIO_PULLUP_DISABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_DISABLE
    };
    gpio_config(&io_conf);

    // 初始状态置低
    gpio_set_level(CONFIG_RELAY_INA_GPIO, 0);
    gpio_set_level(CONFIG_RELAY_INB_GPIO, 0);

    ESP_LOGI(TAG, "Initialized | INA: GPIO%d, INB: GPIO%d",
             CONFIG_RELAY_INA_GPIO, CONFIG_RELAY_INB_GPIO);
    return 0;
}

static void _cn8023a_control(uint8_t ina, uint8_t inb)
{
    if (xSemaphoreTake(relay_mutex, portMAX_DELAY) == pdTRUE)
    {
        gpio_set_level(CONFIG_RELAY_INA_GPIO, ina);
        gpio_set_level(CONFIG_RELAY_INB_GPIO, inb);
        vTaskDelay(pdMS_TO_TICKS(100)); // 维持100ms脉冲
        gpio_set_level(CONFIG_RELAY_INA_GPIO, 0);
        gpio_set_level(CONFIG_RELAY_INB_GPIO, 0);
        xSemaphoreGive(relay_mutex);
    }
}

void cn8023a_open(void)
{
    _cn8023a_control(0, 1);
}

void cn8023a_close(void)
{
    _cn8023a_control(1, 0);
}
